#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 将字典转换为XML
问题: 你想使用一个Python字典存储数据，并将它转换成XML格式。
提示 : 
"""

from xml.etree.ElementTree import Element, tostring

def recipe1():
    s = { 'name': 'GOOG', 'shares': 100, 'price':490.1 }
    e = dict_to_xml('stock', s)
    print(f"{e = }")

    # 添加属性值
    e.set('_id', '1234')
    print(f"{tostring(e) = }")

def recipe2():
    d = { 'name' : '<spam>' }
    print(f"{dict_to_xml_str('item', d) = }")

    e = dict_to_xml('item',d)
    print(f"{tostring(e) = }")

def recipe3():
    '''需要手动去转换这些字符'''
    from xml.sax.saxutils import escape, unescape
    print(f"{escape('<span>') = }")
    print(f"{unescape('&lt;span&gt;') = }")

def dict_to_xml_str(tag, d):
    '''限制只能构造字符串类型的值'''
    parts = ['<{}>'.format(tag)]
    for key, val in d.items():
        parts.append('<{0}>{1}</{0}>'.format(key, val))
    parts.append('</{}>'.format(tag))
    return ''.join(parts)

def dict_to_xml(tag, d):
    '''
    Turn a simple dict of key/value pairs into XML
    '''
    elem = Element(tag)
    for key, val in d.items():
        child = Element(key)
        child.text = str(val)
        elem.append(child)
    return elem

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()

if __name__ == '__main__':
    main()                